package com.harmonyos.studyharmonyos.slice;

import com.harmonyos.studyharmonyos.PlayerAbility;
import com.harmonyos.studyharmonyos.ResourceTable;
import com.harmonyos.studyharmonyos.bean.AdvertisementMo;
import com.harmonyos.studyharmonyos.bean.VideoListMo;
import com.harmonyos.studyharmonyos.bean.VideoTabStyle;
import com.harmonyos.studyharmonyos.helper.provider.AdvertisementProvider;
import com.harmonyos.studyharmonyos.helper.provider.CommonProvider;
import com.harmonyos.studyharmonyos.helper.provider.ViewProvider;
import com.harmonyos.studyharmonyos.player.constant.Constants;
import com.harmonyos.studyharmonyos.util.LogUtils;
import com.harmonyos.studyharmonyos.util.MediaUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 跨设备协同视频列表
 */
public class VediosAbilitySlice extends AbilitySlice {
    private static final String TAG = VediosAbilitySlice.class.getSimpleName();
    private CommonProvider<VideoListMo> commonProvider;//即将上映列表适配器
    private AdvertisementProvider<Component> advertisementProvider;//顶部列表适配器
    private PageSlider advPageSlider;//顶部滚动banner
    private ScheduledExecutorService scheduledExecutor;//定时器
    private int currentPageIndex = 0;//当前显示页下标
    private Runnable slidTask;//主线程任务分发器

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_video);
        initContent();
    }

    private void initContent() {
        initScheduledExecutor();
        initAdvertisement();
        initList();
        startSlidTimer();
    }

    private void initScheduledExecutor() {
        // TODO 1 创建主线程任务分发器
        slidTask = () -> getUITaskDispatcher().asyncDispatch(() -> {
            if (currentPageIndex == advertisementProvider.getCount()) {
                currentPageIndex = 0;
            } else {
                currentPageIndex++;
            }
            advPageSlider.setCurrentPage(currentPageIndex);
        });
        scheduledExecutor = new ScheduledThreadPoolExecutor(1);//创建定时器
    }

    /**
     * 初始化即将上映列表
     */
    private void initList() {
        LogUtils.info(TAG, "begin updateTableView tab view");
        Text playTitle = null;
        if (findComponentById(ResourceTable.Id_video_play_title) instanceof Text) {//控件类型判断
            playTitle = (Text) findComponentById(ResourceTable.Id_video_play_title);
        }
        Font.Builder fb = new Font.Builder(VideoTabStyle.BOLD_FONT_NAME);
        fb.setWeight(Font.BOLD);
        Font newFont = fb.build();
        playTitle.setFont(newFont);//设置字体
        commonProvider = new CommonProvider<VideoListMo>(//创建适配器
                MediaUtil.getPlayListMos(),
                getContext(),
                ResourceTable.Layout_recommend_gv_item) {
            @Override
            protected void convert(ViewProvider holder, VideoListMo item, int position) {
                //ViewHolder数据绑定
                holder.setText(ResourceTable.Id_name_tv, item.getName());
                holder.setText(ResourceTable.Id_content_tv, item.getDescription());
                holder.setImageResource(ResourceTable.Id_image_iv, item.getSourceId());
            }
        };
        ListContainer playListContainer = null;
        if (findComponentById(ResourceTable.Id_video_list_play_view) instanceof ListContainer) {//控件类型判断
            playListContainer = (ListContainer) findComponentById(ResourceTable.Id_video_list_play_view);
        }
        playListContainer.setItemProvider(commonProvider);//绑定适配器
        playListContainer.setItemClickedListener((listContainer, component, index, position) -> startFa(index));//单机单行时，跳转到播放视频页面
    }

    /**
     * TODO 3 初始化顶部banner适配器
     */
    private void initAdvertisement() {
        advertisementProvider = new AdvertisementProvider<>(getAdvertisementComponents());//实例化列表适配器
        Component advViewPager = findComponentById(ResourceTable.Id_video_advertisement_viewpager);
        if (advViewPager instanceof PageSlider) {//控件类型判断
            advPageSlider = (PageSlider) advViewPager;
            advPageSlider.setProvider(advertisementProvider);//绑定适配器
            advPageSlider.setClickedListener(component -> startFa(currentPageIndex));
        } else {
            LogUtils.debug(TAG, "initAdvertisement failed, advertisement_viewpager is not PageSlider");
        }
        PageSliderIndicator advIndicator = null;
        if (findComponentById(ResourceTable.Id_video_advertisement_indicator) instanceof PageSliderIndicator) {//控件类型判断
            advIndicator = (PageSliderIndicator) findComponentById(ResourceTable.Id_video_advertisement_indicator);//实例化指示器
        }
        assert advIndicator != null;
        advIndicator.setItemOffset(VideoTabStyle.INDICATOR_OFFSET);//设置导航点之间的偏移量
        //构建未选中样式
        ShapeElement normalDrawable = new ShapeElement();
        normalDrawable.setRgbColor(RgbColor.fromRgbaInt(Color.WHITE.getValue()));//设置背景色
        normalDrawable.setAlpha(VideoTabStyle.INDICATOR_NORMA_ALPHA);//设置透明度
        normalDrawable.setShape(ShapeElement.OVAL);//设置圆形
        normalDrawable.setBounds(0, 0, VideoTabStyle.INDICATOR_BONDS, VideoTabStyle.INDICATOR_BONDS);//设置间距
        //构建选中样式
        ShapeElement selectedDrawable = new ShapeElement();
        selectedDrawable.setRgbColor(RgbColor.fromRgbaInt(Color.WHITE.getValue()));
        selectedDrawable.setShape(ShapeElement.OVAL);
        selectedDrawable.setBounds(0, 0, VideoTabStyle.INDICATOR_BONDS, VideoTabStyle.INDICATOR_BONDS);

        advIndicator.setItemElement(normalDrawable, selectedDrawable);//设置指示器未选中和选中样式
        advIndicator.setViewPager((PageSlider) advViewPager);//指示器关联PageSlider
    }

    /**
     * 跳转到播放视频页面
     */
    private void startFa(int index) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withBundleName(getBundleName())
                .withAbilityName(PlayerAbility.class.getName()).build();
        intent.setOperation(operation);
        intent.setParam(Constants.INTENT_STARTTIME_PARAM, 0);
        intent.setParam(Constants.VIDEO_URL, index);
        startAbility(intent);
    }

    /**
     * 初始化顶部banner
     *
     * @return AdapterItem集合
     */
    private List<Component> getAdvertisementComponents() {
        List<AdvertisementMo> advertisementMos = MediaUtil.getVideoAdvertisementInfo();//获取本地构建数据集合
        List<Component> componentList = new ArrayList<>(advertisementMos.size());//创建控件集合
        Font.Builder fb = new Font.Builder(VideoTabStyle.BOLD_FONT_NAME);
        fb.setWeight(Font.BOLD);//设置字体加粗
        Font newFont = fb.build();
        for (AdvertisementMo advertisementMo : advertisementMos) {
            Component advRootView = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_video_advertisement_item, null, false);//实例化布局
            Image imgTemp = null;
            if (advRootView.findComponentById(ResourceTable.Id_video_advertisement_poster) instanceof Image) {//控件类型判断
                imgTemp = (Image) advRootView.findComponentById(ResourceTable.Id_video_advertisement_poster);//实例化图片控件
            }
            imgTemp.setPixelMap(advertisementMo.getSourceId());//图片控件赋值
            Text titleTmp = null;
            if (advRootView.findComponentById(ResourceTable.Id_video_advertisement_title) instanceof Text) {//控件类型判断
                titleTmp = (Text) advRootView.findComponentById(ResourceTable.Id_video_advertisement_title);//实例化文本控件
            }
            titleTmp.setText(advertisementMo.getDescription());//文本赋值
            titleTmp.setFont(newFont);//设置字体
            componentList.add(advRootView);//添加到集合
        }

        return componentList;
    }

    /*定时器，定时刷新顶部banner滚动*/
    private void startSlidTimer() {
        /*
         * TODO 2
         * slidTask:执行的任务
         * VideoTabStyle.ADVERTISEMENT_SLID_PROID:首次执行任务的延迟时间
         * VideoTabStyle.ADVERTISEMENT_SLID_DELAY:每次执行任务的间隔时间
         * TimeUnit.SECONDS:间隔单位秒
         */
        scheduledExecutor.scheduleAtFixedRate(slidTask, VideoTabStyle.ADVERTISEMENT_SLID_PROID,
                VideoTabStyle.ADVERTISEMENT_SLID_DELAY, TimeUnit.SECONDS);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onInactive() {
        super.onInactive();
        LogUtils.info(TAG, "is onInactive");
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        LogUtils.info(TAG, "is onForeground");
    }

    @Override
    public void onBackground() {
        super.onBackground();
        LogUtils.info(TAG, "is onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtils.info(TAG, "is onStop");
    }

    @Override
    protected void onBackPressed() {
        LogUtils.info(TAG, "is onBackPressed");
        super.onBackPressed();
    }
}
